<script>
    var ordersApp = angular.module('JxApp', ["ngAnimate", "ng-currency", "ipCookie", "mgcrea.ngStrap", "ngSanitize", "ui.bootstrap.tpls", "ui.bootstrap.datepicker"]);
    var maxRowId;// 当前最大的行号

    ordersApp.controller('OrderModule', function ($scope, $http, $filter) {
        $scope.snPacketArr = [];
        $scope.suppliers = [];
        $scope.packetNumber = 1;
        $scope.packetNumbers = [];
        $scope.supplierDiscount = 100;

        $scope.businessConfig = {zeroPaid: 1, defaultLastPrice: 2, defaultSupplierLastPrice: 2};

        $scope.initOrder = function () {
            //获取全部尺码、颜色数据
            $scope.allSizes = allSizes;
            $scope.allColors = allColors;

            $scope.order = {
                alreadyPaid: 0,
                discount: 100,
                totalAmount: 0,
                finalTotalAmount: 0,
                wipeZero: 0,
                otherCost: 0,
                state: 1,
                businessTime: new Date(),
                remark: '',
                order_type: order_type,
                plan_id: plan_id
            };

            if (firstPageSupplierJson[0]) {
                //默认选择第一个
                $scope.suppliers = firstPageSupplierJson;
                $scope.order.supplier = firstPageSupplierJson[0];
                $scope.order.supplier.val = firstPageSupplierJson[0].id;
                $scope.order.supplierId = firstPageSupplierJson[0].id;
            }
        };

        $scope.initOrder();

        /**
         * 更新列表中的折扣
         */
        $scope.updateDiscount = function () {

            var allRowData = $("#purchaseList").jqGrid("getRowData"); //所有的行的数据

            var goods_noArr = [];
            for (var i = 0; i < allRowData.length; i++) {
                if (allRowData[i]['goods_no']) {
                    goods_noArr.push(allRowData[i]['goods_no']);
                }
            }

            //需要有供应商
            if ($scope.order.supplier.val) {
                $http.post(base + '/admin/inner/supplier/getSupplierWithPrices.ac', $.param({
                    id: $scope.order.supplier.val,
                    goods_noArr: goods_noArr
                }), {
                    headers:
                        {
                            'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
                        }
                }).success(function (result) {
                    if (result.statusCode == 1) {
                        $scope.supplierDiscount = (result.object.objSupplier && result.object.objSupplier.discount) ? result.object.objSupplier.discount : 100;
                        var rowIds = $("#purchaseList").jqGrid('getDataIDs'); //获取所有行Id
                        $scope.lastSupplierPrices = result.object.goodsPricesList;
                        for (var i = 0; i < rowIds.length; i++) {
                            var thisRow = $("#purchaseList").jqGrid("getRowData", rowIds[i]); //当前行数据
                            var property = $scope.getGoodPropertyAfterCalc(thisRow);

                            $("#purchaseList").setRowData(rowIds[i], {
                                supplierPrice: property.supplierPriceTemp,
                                supplierTruePrice: property.supplierTruePriceTemp,
                                market_price: property.market_priceTemp,
                                price: property.priceTemp,
                                truePrice: property.truePriceTemp,
                                discount: property.discountTemp,
                                amount: property.amountTemp,
                                trueAmount: property.trueAmountTemp
                            });
                        }
                        //更新合计行上的合计指标
                        updateTotalNumbers();

                        setTimeout(function () {
                            $scope.$apply(function (scope) {
                                if (scope.businessConfig.zeroPaid == 1) {
                                    scope.order.alreadyPaid = 0;
                                } else {
                                    scope.order.alreadyPaid = scope.order.finalTotalAmount;
                                }
                            });
                        });
                    }
                });
            }
        };

        /**
         * 获取该商品计算后的相关属性
         */
        $scope.getGoodPropertyAfterCalc = function (good) {
            var priceTemp = setScale(good['price'], 2);
            var market_priceTemp = '';
            var supplierPriceTemp = '';
            var supplierTruePriceTemp = '';
            var priceTempObject = getObjectByObject($scope.lastSupplierPrices, {
                goods_no: good.goods_no,
                colorId: parseInt(good.colorId),
                sizeId: parseInt(good.sizeId)
            });
            if (priceTempObject) {
                market_priceTemp = (priceTempObject.market_price || priceTempObject.market_price === 0) ? setScale(priceTempObject.market_price, 2) : '';
                supplierPriceTemp = (priceTempObject.supplierPrice || priceTempObject.supplierPrice === 0) ? setScale(priceTempObject.supplierPrice, 2) : '';
                supplierTruePriceTemp = (priceTempObject.supplierTruePrice || priceTempObject.supplierTruePrice === 0) ? setScale(priceTempObject.supplierTruePrice, 2) : '';
            } else {
                priceTempObject = getObject($scope.lastSupplierPrices, "goods_no", good.goods_no);
                if (priceTempObject) {
                    market_priceTemp = (priceTempObject.market_price || priceTempObject.market_price === 0) ? setScale(priceTempObject.market_price, 2) : '';
                }
            }

            //设置单价,优化级:上次单价>客户分类单价>批发价
            if ((supplierPriceTemp || supplierPriceTemp === 0) && $scope.autoChoseLastPriceEnable) {
                priceTemp = supplierPriceTemp;
            } else if (market_priceTemp || market_priceTemp === 0) {
                priceTemp = market_priceTemp;
            }

            var truePriceTemp = 0;
            var discountTemp = 0;
            var amountTemp = 0;
            var trueAmountTemp = 0;

            if ((supplierTruePriceTemp || supplierTruePriceTemp === 0) && $scope.autoChoseLastPriceEnable) {
                //如果有上次折后价，则本次折后价也按上次折后价来
                if (priceTemp === 0) {
                    //如果上次价格为0，则折后价也为0，折扣为100%
                    truePriceTemp = 0;
                    discountTemp = 100;
                    amountTemp = 0;
                    trueAmountTemp = 0;
                } else {
                    truePriceTemp = supplierTruePriceTemp;
                    discountTemp = setScale(accMul(accDiv(supplierTruePriceTemp, priceTemp), 100), 2);
                    amountTemp = accMul(priceTemp, good.quantity);
                    trueAmountTemp = accMul(supplierTruePriceTemp, good.quantity);
                }
            } else {
                truePriceTemp = setScale(accDiv(accMul(priceTemp, $scope.supplierDiscount), 100), 2);
                discountTemp = $scope.supplierDiscount;
                amountTemp = accMul(priceTemp, good.quantity);
                trueAmountTemp = accMul(good.quantity, setScale(accDiv(accMul(priceTemp, $scope.supplierDiscount), 100), 2));
            }

            return {
                supplierPriceTemp: supplierPriceTemp,
                supplierTruePriceTemp: supplierTruePriceTemp,
                market_priceTemp: market_priceTemp,
                priceTemp: priceTemp,
                truePriceTemp: truePriceTemp,
                discountTemp: discountTemp,
                amountTemp: amountTemp,
                trueAmountTemp: trueAmountTemp
            }
        };

        /**
         * 商品输入框有变动的时候，加载商品
         * @param good
         */
        $scope.changAutoGoods = function (obj) {
            $scope.goods = [];
            $scope.loadGood($(obj).val());

            //获取当前rowId
            $scope.rowId = $(obj).parent().parent().parent().attr("id");
            //指向当前编辑的表格
            $scope.curEditGoodInput = $(obj);
            $scope.showAutoGoods = true;


            var top = ($(obj).offset().top + $(obj).outerHeight() - 127) + 'px';
            var width = ($(obj).width() + 18) + 'px';
            var left = (($(obj).offset().left) - 210) + 'px';
            $scope.autoGoodsStyle = {top: top, width: width, left: left};

        };

        $scope.loaddingMsg = "加载中...";

        /**
         * 加载商品
         * @param good
         */
        $scope.loadGood = function (inputKey) {
            $scope.addGoodTip = false;
            $scope.loaddingMsg = "加载中...";
            var paramsJson = {searchKey: inputKey};
            $http.get("{{ route('admin.shop.public.goodsSelect') }}", {params: paramsJson}).success(function (data) {
                $scope.goods = data.optionList.data;
                if ($scope.goods.length == 0) {
                    $scope.addGoodTip = true;
                } else {
                    $scope.addGoodTip = false;
                    $scope.loaddingMsg = "点击选择";
                }

            }).error(function (e) {
                // 错误是聚焦在body上，防止多次触发请求
                $('body').click();
            });
        };

        /**
         * 在表格中自动完成输入框中点选商品
         * @param good
         */
        $scope.selAutoGood = function (good) {
            if (aboveMaxQuantity()) {
                return;
            }

            var rowData = $("#purchaseList").jqGrid("getRowData", $scope.rowId);
            if ($scope.curEditGoodInput != undefined) {

                $scope.curEditGoodInput.val(good.name);
            }
            $scope.selGood = good;
            $scope.showAutoGoods = false;
            //准备弹出二维录入框
            $scope.currentRowData = {
                quantity: 1,
                price: good.factory_price,
                amount: good.factory_price,
                sizeIds: good.sizeIds,
                colorIds: good.colorIds,
                goods_no: good.goods_no,
                blandId: good.brand_id,
                name: good.name,
                goods_id: good.id,
                barCode: good.goods_barcode,
                discount: rowData.discount
            };

            $scope.initPacketNumber(good.goods_no, 1);

            var isShowSel = $scope.showAndProTwoDimensionSel($scope.currentRowData);
            if (isShowSel) {
                $("#purchaseList").setRowData($scope.rowId, {name: $scope.currentRowData['name']});
            } else {
                delRow(null, $scope.rowId);
            }
        };

        /**
         * 获取包装数值
         */
        $scope.initPacketNumber = function (goods_no, packetNumber) {
            var flag = false;
            for (var i = 0; i < $scope.snPacketArr.length; i++) {
                for (var snPacket in $scope.snPacketArr[i]) {
                    if (snPacket == $scope.currentRowData[goods_no]) {
                        if (!$scope.snPacketArr[i][snPacket]) {
                            $scope.packetNumber = 1;
                        } else {
                            $scope.packetNumber = $scope.snPacketArr[i][snPacket];
                        }
                        //复制为新增时没有$scope.packetNumbers
                        if (!$scope.packetNumbers || $scope.packetNumber != 1) {
                            $scope.getPacketNumber($scope.packetNumber);
                        }
                        $scope.packetNumberDisabled = true;
                        flag = true;
                        break;
                    }
                }
            }

            if (!flag) {
                $scope.packetNumber = packetNumber;
                $scope.packetNumberDisabled = false;
                //获取商品打包数
                $scope.getPacketNumber(packetNumber);
            }
        };

        /** 获取商品属性里的包装数*/
        $scope.getPacketNumber = function (packetNumber) {
            if (!packetNumber || packetNumber == 1) {
                $scope.packetNumbers = [1];
            } else {
                $scope.packetNumbers = [1, packetNumber]
            }
        };

        //当前商品包含的尺码数据
        $scope.currentSizes = [];
        $scope.currentColors = [];

        /**
         * 处理并显示二维录入框
         */
        $scope.showAndProTwoDimensionSel = function (currentRowData) {
            //当前商品所拥有的尺码
            $scope.currentSizes = [];
            //当前商品所拥有的颜色
            $scope.currentColors = [];

            //行货号
            var curGoodSn = currentRowData['goods_no'];
            //商品名称
            var curGoodName = currentRowData['name'];
            if (curGoodSn == undefined || curGoodSn == "") {
                return false;
            }

            var tmpShopId;
            if ($scope.order.order_type == 'transfer') {
                if (!$scope.order.outShopId) {
                    $scope.warningMsg = "请选择调出门店";
                    showAlert();
                    return;
                }

                if (!$scope.order.inShopId) {
                    $scope.warningMsg = "请选择调入门店";
                    showAlert();
                    return;
                }

                if ($scope.order.inShopId == $scope.order.outShopId) {
                    $scope.warningMsg = "调出门店 与 调入门店不能相同";
                    showAlert();
                    return;
                }

                tmpShopId = $scope.order.outShopId;
            } else {
                tmpShopId = '{{ session('shop_id') }}';
            }

            $scope.getStoredCount(curGoodSn, parseInt(tmpShopId));
            //为了不保留原来的输入数据，这里重新申请了空间。
            $scope.currentSizes = $filter('filter')(angular.copy(idStringToObjectArray($scope.allSizes, currentRowData['sizeIds'], 'id', ',')), {
                status: 1
            });
            $scope.currentColors = $filter('filter')(angular.copy(idStringToObjectArray($scope.allColors, currentRowData['colorIds'], 'id', ',')), {
                status: 1
            });

            if ($scope.currentSizes.length == 0) {
                $scope.warningMsg = '商品 【' + curGoodSn + ' ' + curGoodName + '】没有可用的尺码！';
                showAlert();
                return false;
            }
            if ($scope.currentColors.length == 0) {
                $scope.warningMsg = '商品 【' + curGoodSn + ' ' + curGoodName + '】没有可用的颜色！';
                showAlert();
                return false;
            }

            //二维录入中，横向选中下标
            $scope.selIndexX = 0;
            //二维录入中，竖向选中下标
            $scope.selIndexY = 0;
            $("#goods" + $scope.selIndexY + "_" + $scope.selIndexX).focus();

            $scope.showTwoDimension = true;
            $("#twoDisDiv").dialog({
                title: currentRowData.name + " " + currentRowData.goods_no,
                dialogClass: 'twoDisDiv'
            });

            $("#twoDisDiv").dialog("open");

            /*$scope.updateSupplierPrice($scope.order.supplierId, [curGoodSn], function (result) {
                $scope.getOneGoodSupplierPrices(result, {goods_no: curGoodSn});
                $("#twoDisDiv").dialog("open");
            });*/

            $("#purchaseList").jqGrid("saveCell", lastrow, lastcell);

            return true;
        };

        /**
         * 查询库存
         */
        $scope.storedCount = [];

        $scope.getStoredCount = function (curGoodSn, shop_id) {
            $http.get('{{route('admin.shop.public.getStoredCount')}}?goods_no=' + encodeURIComponent(curGoodSn) + '&shop_id=' + shop_id).success(function (result) {
                for (var i = 0; i < result.data.length; i++) {
                    var stored = result.data[i];
                    if ($scope.storedCount[stored.colorId] == undefined) {
                        $scope.storedCount[stored.colorId] = [];
                    }

                    $scope.storedCount[stored.colorId][stored.sizeId] = stored;
                }
            });
        };

        /**
         * 二维录入框中，点击输入框
         * @param keyEvent
         */
        $scope.clickInput = function (keyEvent) {
            var target = keyEvent.target;
            var targetX = target.getAttribute('indexX');
            var targetY = target.getAttribute('indexY');
            $scope.selIndexX = targetX;
            $scope.selIndexY = targetY;
        };

        /* 二维录入框批量设置所有数量*/
        $scope.allNumberBatchSet = function () {
            for (var i = 0; i < $scope.currentColors.length; i++) {
                for (var j = 0; j < $scope.currentSizes.length; j++) {
                    $scope.currentColors[i][$scope.currentSizes[j].id] = $scope.twoDisTableSetNumber;
                }
            }
            $scope.twoDisTableSetNumber = '';
            $scope.allNumberBatchSetting = false;
            $("#twoDisConfirmBtn").focus();
        };

        /* 二维录入框批量设置某一颜色的所有数量*/
        $scope.colorNumberBatchSet = function () {
            var colorIndex = $scope.currentSettingId;
            for (var i = 0; i < $scope.currentSizes.length; i++) {
                $scope.currentColors[colorIndex][$scope.currentSizes[i].id] = $scope.twoDisTableSetNumber;
            }
            $scope.twoDisTableSetNumber = '';
            $scope.currentSettingId = '';
            $scope.colorNumberBatchSetting = false;
            $("#twoDisConfirmBtn").focus();
        };

        /* 二维录入框批量设置某一尺码的所有数量*/
        $scope.sizeNumberBatchSet = function (sizeId) {
            var sizeId = $scope.currentSettingId;
            for (var i = 0; i < $scope.currentColors.length; i++) {
                $scope.currentColors[i][sizeId] = $scope.twoDisTableSetNumber;
            }
            $scope.twoDisTableSetNumber = '';
            $scope.currentSettingId = '';
            $scope.sizeNumberBatchSetting = false;
            $("#twoDisConfirmBtn").focus();
        };

        /* 二维录入框指设置取消 */
        $scope.numberBatchSetCancel = function () {
            $scope.twoDisTableSetNumber = '';
            $scope.allNumberBatchSetting = false;
            $scope.colorNumberBatchSetting = false;
            $scope.sizeNumberBatchSetting = false;
            $("#twoDisConfirmBtn").focus();
        };

        /* 二维录入框点击尺码显示设置数量 */
        $scope.toSetSizeNumber = function (index) {
            $scope.currentSettingId = $scope.currentSizes[index].id;
            $scope.colorNumberBatchSetting = false;
            $scope.allNumberBatchSetting = false;
            $scope.sizeNumberBatchSetting = true;
            $scope.numberBatchSetTips = "（批量设置尺码“" + $scope.currentSizes[index].name + "”下所有单品的数量）";
            setTimeout(function () {
                $("#twoDisTableSetNumber").focus();
            });
        };
        /* 二维录入框点击颜色显示设置数量 */
        $scope.toSetColorNumber = function (index) {
            $scope.currentSettingId = index;
            $scope.sizeNumberBatchSetting = false;
            $scope.allNumberBatchSetting = false;
            $scope.colorNumberBatchSetting = true;
            $scope.numberBatchSetTips = "（批量设置颜色“" + $scope.currentColors[index].name + "”下所有单品的数量）";
            setTimeout(function () {
                $("#twoDisTableSetNumber").focus();
            });
        };
        /* 二维录入框点击"批量设置所有"显示设置数量 */
        $scope.toSetAllNumber = function () {
            $scope.allNumberBatchSetting = true;
            setTimeout(function () {
                $("#twoDisTableSetNumber").focus();
            });
        };

        /**
         * 二维录入确定
         */
        $scope.twoDisConfirm = function () {
            //获取输入的数据
            var insertModels = [];

            if ($scope.storedCount == undefined) {
                $scope.storedCount = [];
            }

            for (var i = 0; i < $scope.currentColors.length; i++) {
                var color = $scope.currentColors[i];
                for (var j = 0; j < $scope.currentSizes.length; j++) {

                    var size = $scope.currentSizes[j];
                    if (color[size.id] != undefined) {
                        if ($scope.storedCount[$scope.currentColors[i].id] == undefined) {
                            $scope.storedCount[$scope.currentColors[i].id] = [];
                        }

                        $scope.currentRowData.sizeId = size.id;
                        $scope.currentRowData.colorId = color.id;
                        $scope.currentRowData.quantity = accMul(color[size.id], $scope.packetNumber);

                        if (($scope.order.order_type == 'REJECT' || $scope.order.order_type == 'transfer') && $scope.storedCount[color.id][size.id].number < $scope.currentRowData.quantity) {
                            $scope.warningMsg = $scope.storedCount[color.id][size.id].colorName + " - " + $scope.storedCount[color.id][size.id].sizeName + "当前库存：" + $scope.storedCount[color.id][size.id].number + "，请重新输入退货数量。";
                            showAlert();
                            break;
                            return;
                        }


                        var property = $scope.getGoodPropertyAfterCalc($scope.currentRowData);

                        var newModel = {
                            goods_no: $scope.currentRowData.goods_no,
                            goodName: $scope.currentRowData.name,
                            barCode: $scope.currentRowData.barCode,
                            name: $scope.currentRowData.name,
                            goods_id: $scope.currentRowData.goods_id,
                            discount: property.discountTemp,
                            sizeId: size.id,
                            sizeName: size.name,
                            colorId: color.id,
                            colorName: color.name,
                            currentSku: $scope.storedCount[color.id][size.id].sku,
                            quantity: accMul(color[size.id], $scope.packetNumber),
                            price: property.priceTemp,
                            truePrice: property.truePriceTemp,
                            colorIds: $scope.currentRowData.colorIds,
                            sizeIds: $scope.currentRowData.sizeIds,
                            amount: property.amountTemp,
                            trueAmount: property.trueAmountTemp,
                            factoryPrice: property.factoryPriceTemp,
                            supplierPrice: property.supplierPriceTemp,
                            supplierTruePrice: property.supplierTruePriceTemp,
                            number: $scope.storedCount[color.id][size.id].number,
                            packetNumber: $scope.packetNumber,
                            packetCount: color[size.id]
                        };

                        insertModels.push(newModel);
                        $scope.notSaveOrder = true;
                        if (aboveMaxQuantity(insertModels)) {
                            return;
                        }
                    }
                }
            }


            //把输入的数据插入订单-商品明细表中
            if (maxRowId == undefined) {
                maxRowId = $("#purchaseList").jqGrid('getDataIDs').length;
            }

            /*判断新增加的单品是否已在列表中存在，如果存在则把新增加单品的数量添加到已存在的记录中*/
            var sameNumber = 0;
            //二维录入框中的商品存在于原商品明细表标志（如果存在则合并数量）
            var notDeleteFlag = false;
            //二维录入框中的商品与当前编辑行商品一致，则不删除当前行
            var rowIds = $("#purchaseList").jqGrid('getDataIDs');
            var snPacket = {};
            for (var i = 0; i < insertModels.length; i++) {

                var existsSameFlag = false;
                for (var j = 0; j < rowIds.length; j++) {
                    var thisRow = $("#purchaseList").jqGrid("getRowData", rowIds[j]);
                    if (thisRow['goods_no'] == insertModels[i]['goods_no'] && thisRow['colorId'] == insertModels[i]['colorId'] && thisRow['sizeId'] == insertModels[i]['sizeId']) {

                        //如果是与当前行商品一致，则不合并数量，而是把数量覆盖
                        if (rowIds[j] == $scope.rowId) {
                            $("#purchaseList").setRowData(rowIds[j], {
                                goods_id: parseInt(insertModels[i]['goods_id']),
                                packetCount: parseInt(insertModels[i]['packetCount']),
                                packetNumber: parseInt(insertModels[i]['packetNumber']),
                                quantity: parseInt(insertModels[i]['quantity']),
                                amount: accMul(parseInt(insertModels[i]['quantity']), thisRow['price']),
                                currentSku: $scope.storedCount[thisRow['colorId']][thisRow['sizeId']].sku,
                                trueAmount: accMul(parseInt(insertModels[i]['quantity']), thisRow['truePrice'])
                            });
                            notDeleteFlag = true;
                        } else {
                            if (thisRow['packetNumber'] != insertModels[i]['packetNumber']) {
                                $("#purchaseList").setRowData(rowIds[j], {
                                    goods_id: parseInt(insertModels[i]['goods_id']),
                                    currentSku: $scope.storedCount[thisRow['colorId']][thisRow['sizeId']].sku,
                                    packetCount: parseInt(thisRow['packetCount']) + parseInt(insertModels[i]['packetCount']),
                                    packetNumber: insertModels[i]['packetNumber'],
                                    quantity: accMul(parseInt(thisRow['packetCount']), insertModels[i]['packetNumber']) + parseInt(insertModels[i]['quantity']),
                                    amount: accMul((accMul(parseInt(thisRow['packetCount']), insertModels[i]['packetNumber']) + parseInt(insertModels[i]['quantity'])), thisRow['price']),
                                    trueAmount: accMul((accMul(parseInt(thisRow['packetCount']), insertModels[i]['packetNumber']) + parseInt(insertModels[i]['quantity'])), thisRow['truePrice'])
                                });
                            } else {
                                $("#purchaseList").setRowData(rowIds[j], {
                                    goods_id: parseInt(insertModels[i]['goods_id']),
                                    currentSku: $scope.storedCount[thisRow['colorId']][thisRow['sizeId']].sku,
                                    packetCount: parseInt(thisRow['packetCount']) + parseInt(insertModels[i]['packetCount']),
                                    packetNumber: parseInt(insertModels[i]['packetNumber']),
                                    quantity: parseInt(thisRow['quantity']) + parseInt(insertModels[i]['quantity']),
                                    amount: accMul((parseInt(thisRow['quantity']) + parseInt(insertModels[i]['quantity'])), thisRow['price']),
                                    trueAmount: accMul((parseInt(thisRow['quantity']) + parseInt(insertModels[i]['quantity'])), thisRow['truePrice'])
                                });
                            }
                        }

                        existsSameFlag = true;
                        ++sameNumber;
                        break;
                    }
                }

                var spFlag = false;
                for (var k = 0; k < $scope.snPacketArr.length; k++) {
                    for (var sp in $scope.snPacketArr[k]) {
                        if (sp == insertModels[i]['goods_no']) {
                            spFlag = true;
                            break;
                        }
                    }
                }

                if (!spFlag) {
                    //由于开过单的商品下次就只有一个选项，所以此处不需要再判定是否已经有开过此商品
                    snPacket[insertModels[i]['goods_no']] = insertModels[i]['packetNumber'];
                    $scope.snPacketArr.push(snPacket);
                }

                if (!existsSameFlag) {
                    maxRowId = maxRowId + 1;
                    if (i - sameNumber == 0) {
                        $('#purchaseList').jqGrid('addRowData', maxRowId, insertModels[i], "after", parseInt($scope.rowId));
                    } else {
                        $('#purchaseList').jqGrid('addRowData', maxRowId, insertModels[i], "after", maxRowId - 1);
                    }
                }
            }

            if (!notDeleteFlag && $("#purchaseList").jqGrid('getDataIDs').length > 1) {
                $("#purchaseList").jqGrid("delRowData", $scope.rowId);
            }

            if ($("#purchaseList").jqGrid('getDataIDs').length < 6) {
                addNewEmptyRow();
            }

            //更新合计行上的合计指标
            updateTotalNumbers();

            setTimeout(function () {
                $scope.$apply(function (scope) {
                    if (scope.businessConfig.zeroPaid == 1) {
                        scope.order.alreadyPaid = 0;
                    } else {
                        scope.order.alreadyPaid = scope.order.finalTotalAmount;
                    }
                });
            });

            var emptyRowId = $scope.getEmptyRowId();
            if (emptyRowId == -1) {
                addNewEmptyRow();
                emptyRowId = maxRowId;
            }
            var trs = $("table#purchaseList tr");
            var index = trs.index($("#purchaseList tr[id='" + emptyRowId + "']"));
            if ($scope.barCodeFocus) {
                $scope.barCode = "";
                $("#barCode").focus();
            } else if (index != -1) {
                //var nextRowId =index+1;//下一空白行ID
                setTimeout(function () {
                    $('#purchaseList').editCell(index, 8, true);
                    //聚焦下一空白行
                }, 50);
            }

            $("#twoDisDiv").dialog("close");
        };

        $scope.getEmptyRowId = function () {
            var rowIds = $("#purchaseList").jqGrid("getDataIDs");
            for (var j = 0; j < rowIds.length; j++) {
                var thisRow = $("#purchaseList").jqGrid("getRowData", rowIds[j]); //当前行数据
                if (thisRow['name'] == "") {
                    return rowIds[j];
                }
            }
            return -1;
        };

        /**
         * 获取该商品计算后的相关属性
         */
        $scope.getGoodPropertyAfterCalc = function (good) {
            var priceTemp = setScale(good['price'], 2);
            var factoryPriceTemp = '';
            var supplierPriceTemp = '';
            var supplierTruePriceTemp = '';
            var priceTempObject = getObjectByObject($scope.lastSupplierPrices, {
                goods_no: good.goods_no,
                colorId: parseInt(good.colorId),
                sizeId: parseInt(good.sizeId)
            });

            if (priceTempObject) {
                factoryPriceTemp = (priceTempObject.factoryPrice || priceTempObject.factoryPrice === 0) ? setScale(priceTempObject.factoryPrice, 2) : '';
                supplierPriceTemp = (priceTempObject.supplierPrice || priceTempObject.supplierPrice === 0) ? setScale(priceTempObject.supplierPrice, 2) : '';
                supplierTruePriceTemp = (priceTempObject.supplierTruePrice || priceTempObject.supplierTruePrice === 0) ? setScale(priceTempObject.supplierTruePrice, 2) : '';
            } else {
                priceTempObject = getObject($scope.lastSupplierPrices, "goods_no", good.goods_no);
                if (priceTempObject) {
                    factoryPriceTemp = (priceTempObject.factoryPrice || priceTempObject.factoryPrice === 0) ? setScale(priceTempObject.factoryPrice, 2) : '';
                }
            }

            //设置单价,优化级:上次单价>客户分类单价>批发价
            if ((supplierPriceTemp || supplierPriceTemp === 0) && $scope.autoChoseLastPriceEnable) {
                priceTemp = supplierPriceTemp;
            } else if (factoryPriceTemp || factoryPriceTemp === 0) {
                priceTemp = factoryPriceTemp;
            }

            var truePriceTemp = 0;
            var discountTemp = 0;
            var amountTemp = 0;
            var trueAmountTemp = 0;

            //如果有上次折后价，则本次折后价也按上次折后价来
            if ((supplierTruePriceTemp || supplierTruePriceTemp === 0) && $scope.autoChoseLastPriceEnable) {
                //如果上次价格为0，则折后价也为0，折扣为100%
                if (priceTemp === 0) {
                    truePriceTemp = 0;
                    discountTemp = 100;
                    amountTemp = 0;
                    trueAmountTemp = 0;
                } else {
                    truePriceTemp = supplierTruePriceTemp;
                    discountTemp = setScale(accMul(accDiv(supplierTruePriceTemp, priceTemp), 100), 2);
                    amountTemp = accMul(priceTemp, good.quantity);
                    trueAmountTemp = accMul(supplierTruePriceTemp, good.quantity);
                }
            } else {
                truePriceTemp = setScale(accDiv(accMul(priceTemp, $scope.supplierDiscount), 100), 2);
                discountTemp = $scope.supplierDiscount;
                amountTemp = accMul(priceTemp, good.quantity);
                trueAmountTemp = accMul(good.quantity, setScale(accDiv(accMul(priceTemp, $scope.supplierDiscount), 100), 2));
            }

            return {
                supplierPriceTemp: supplierPriceTemp,
                supplierTruePriceTemp: supplierTruePriceTemp,
                factoryPriceTemp: factoryPriceTemp,
                priceTemp: priceTemp,
                truePriceTemp: truePriceTemp,
                discountTemp: discountTemp,
                amountTemp: amountTemp,
                trueAmountTemp: trueAmountTemp
            }
        };

        /**
         * 保存草稿
         */
        $scope.saveOrder = function ($event) {
            $("#purchaseList").jqGrid("saveCell", lastrow, lastcell);
            stopEvent($event);
            //所有的行的数据
            var rowData = $("#purchaseList").jqGrid("getRowData");
            if (rowData.length < 1) {
                alert("请输入采购商品信息！");
                return false;
            }

            if ($scope.order.order_type == 'take_stock') {
                $scope.saveUrl = "{{ route('admin.shop.take.stock.store') }}";
            } else if ($scope.order.order_type == 'transfer') {
                $scope.saveUrl = "{{ route('admin.shop.transfer.store') }}";
            } else {
                $scope.saveUrl = "{{ route('admin.shop.purchase.store') }}";
            }

            $scope.loadingTips = "保存中...";
            $scope.saveOrderThread(rowData);
        };

        /**
         * 订单提供线程
         */
        $scope.saveOrderThread = function (rowData) {
            //完整的商品数据
            $scope.orderGoods = [];
            if (($scope.order.trueTotalAmount && $scope.order.trueTotalAmount > 100000000)
                || ($scope.order.totalAmount && $scope.order.totalAmount > 100000000)) {
                $scope.warningMsg = "金额、实付金额不能超过1亿.";
                showAlert();
                return;
            }

            if ($scope.order.order_type == 'transfer') {
                if (!$scope.order.outShopId) {
                    $scope.warningMsg = "请选择调出门店";
                    showAlert();
                    return;
                }

                if (!$scope.order.inShopId) {
                    $scope.warningMsg = "请选择调入门店";
                    showAlert();
                    return;
                }

                if ($scope.order.inShopId == $scope.order.outShopId) {
                    $scope.warningMsg = "调出门店 与 调入门店不能相同";
                    showAlert();
                    return;
                }
            }

            if (!$scope.order.businessTime) {
                $scope.warningMsg = "请选择日期";
                showAlert();
                return;
            }

            var now = new Date();
            $scope.order.businessTime = now.getFullYear() + '-' + now.getMonth() + '-' + now.getDate();

            //检验商品
            for (var i = 0; i < rowData.length; i++) {
                if (rowData[i].goods_no != undefined && rowData[i].goods_no != "") {
                    if (rowData[i].colorId == undefined || rowData[i].colorId == "") {
                        setTimeout(function () {
                            //设置聚焦
                            $('#purchaseList').editCell(i + 1, 12, true);
                        }, 50);
                        $scope.warningMsg = "请选择颜色.";
                        showAlert();
                        return;
                    }
                    if (rowData[i].sizeId == undefined || rowData[i].sizeId == "") {
                        setTimeout(function () {
                            //设置聚焦
                            $('#purchaseList').editCell(i + 1, 13, true);
                        }, 50);
                        $scope.warningMsg = "请选择尺码.";
                        showAlert();
                        return;
                    }
                    if (rowData[i].quantity == undefined || rowData[i].quantity == "") {
                        setTimeout(function () {
                            //设置聚焦
                            $('#purchaseList').editCell(i + 1, 15, true);
                        }, 50);
                        $scope.warningMsg = "请输入数量.";
                        showAlert();
                        return;
                    }

                    if ($scope.order.supplierId == undefined || $scope.order.supplierId == '') {
                        $scope.warningMsg = "请选择供应商.";
                        showAlert();
                        return;
                    }

                    $scope.orderGoods.push({
                        goods_name: rowData[i].name,
                        goods_no: rowData[i].goods_no,
                        goods_id: rowData[i].goods_id,
                        currentSku: rowData[i].currentSku,
                        color: rowData[i].colorName,
                        color_id: rowData[i].colorId,
                        size: rowData[i].sizeName,
                        size_id: rowData[i].sizeId,
                        quantity: rowData[i].quantity,
                        beforeNumber: rowData[i].number,
                        price: rowData[i].price,
                        truePrice: rowData[i].truePrice,
                        amount: rowData[i].amount,
                        trueAmount: rowData[i].trueAmount,
                        discount: rowData[i].discount,
                        packetNumber: rowData[i].packetNumber,
                        showOrder: i
                    });
                } else if (i == 0) {

                    setTimeout(function () {
                        $('#purchaseList').editCell(i + 1, 8, true);
                    }, 50);
                    $scope.warningMsg = "请选择商品.";
                    showAlert();
                    return;
                }
            }

            //$scope.loadingOrder = true;
            //提交订单
            $http.post($scope.saveUrl, $.param({
                order: angular.toJson($scope.order),
                goods: angular.toJson($scope.orderGoods)
            }), {
                headers:
                    {
                        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
                    }
            }).success(function (result) {
                //$scope.loadingOrder = false;
                //var orderid = $scope.order.id;
                if (result.status) {
                    // 如果单据id不存在的情况在上传
                    swal({
                        title: "保存成功！",
                        text: "",
                        type: "success"
                    }, function () {
                        if ($scope.order.order_type == 'PURCHASE') {
                            location = '{{ route('admin.shop.purchase.index') }}';
                        } else if ($scope.order.order_type == 'REJECT') {
                            location = '{{ route('admin.shop.reject.index') }}';
                        } else if ($scope.order.order_type == 'take_stock') {
                            location = '{{ route('admin.shop.take.stock.plan') }}';
                        } else if ($scope.order.order_type == 'transfer') {
                            location = '{{ route('admin.shop.transfer.index') }}';
                        }
                    });
                    //$("#listGrid").trigger("reloadGrid");
                    //$scope.loadOneOrder(result.object.purchaseSn);
                    //$scope.getSupplierInfo();
                } else {
                    $scope.warningMsg = result.message;
                    showAlert();
                }
            }).error(function () {
                $scope.loadingOrder = false;
            });
        };
        //订单提供线程end

        /*$scope.updateSupplierPrice = function (supplierId, goods_noArr, callback, otherParamter) {
            $http.post(base + '/admin/inner/supplier/getSupplierWithPrices.ac', $.param({
                id: supplierId,
                goods_noArr: goods_noArr
            }), {
                headers:
                    {
                        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
                    }
            }).success(function (result) {
                if (result.statusCode == 1) {
                    $scope.supplierDiscount = (result.object.objSupplier && result.object.objSupplier.discount) ? result.object.objSupplier.discount : 100;
                    if (callback) {
                        callback(result.object, otherParamter);
                    }
                }

            });
        };*/

        /*$scope.getOneGoodSupplierPrices = function (result, otherParamter) {
            if (angular.isArray($scope.lastSupplierPrices)) {

                //从价格信息组中剔除当前商品的旧价格信息
                for (var priceTemp in $scope.lastSupplierPrices) {
                    if (priceTemp['goods_no'] == otherParamter.goods_no) {
                        //remove($scope.lastSupplierPrices, priceTemp);
                        $scope.lastSupplierPrices.remove(priceTemp);
                    }
                }
                $scope.lastSupplierPrices = $scope.lastSupplierPrices.concat(result.goodsPricesList);
            } else {
                $scope.lastSupplierPrices = result.goodsPricesList;
            }
        };*/
    });

    /**
     * 显示弹框
     */
    var timeout;

    function showAlert() {
        if (timeout != undefined) {
            clearTimeout(timeout);
        }

        $('.alert').css("zIndex", 1005).show();
        timeout = setTimeout(function () {
            $(".alert").hide();
        }, 3000);
    }


    function aboveMaxQuantity(insertModels) {
        var rowLength = $("#purchaseList").jqGrid("getDataIDs").length;
        var availableRows = getScope("OrderCtrl").order.totalAvailableRows;
        if (availableRows != null && availableRows != undefined) {
            if (insertModels && (availableRows + insertModels.length) > 501) {
                getScope("OrderCtrl").warningMsg = "列表中的商品过多，最多只能有500条记录";
                showAlert();
                return true;
            }
        }
        return false;
    }

    $(document).ready(
        function () {
            /**
             * 自定义商品编辑生成函数
             * @param value
             * @param options
             * @returns {string}
             */
            function goodElement(value, options) {
                var t = '<input type="text"  maxlength="128" placeholder="货号、名称" oninput="changAutoGoods(this)" onfocus ="loadGoodsFirst(this)" onkeydown="goodsSearchPress(event,this)" autocomplete="off" class="textbox goodsAuto" value="' + value + '" ><span  class="ui-icon-ellipsis" onclick="showTwoDimensionSel(this)"></span>';

                return t;
            }

            /**
             * 自定义尺码编辑生成函数
             * @param value
             * @param options
             * @returns {string}
             */
            function sizeElement(value, options) {

                var t = '<input type="text" placeholder="点击选择" readonly onfocus="showAutoSizes(this)" class="textbox goodsAuto" value="' + value + '" ><span class="ui-icon-triangle-1-s"></span>';

                return t;
            }

            /**
             * 自定义颜色编辑生成函数
             * @param value
             * @param options
             * @returns {string}
             */
            function colorElement(value, options) {

                var t = '<input type="text" placeholder="点击选择" readonly onfocus="showAutoColors(this)" class="textbox goodsAuto" value="' + value + '" ><span class="ui-icon-triangle-1-s"></span>';

                return t;
            }

            /**
             * 自定义单价编辑生成函数
             * @param value
             * @param options
             * @returns {string}
             */
            function priceElement(value, options) {
                var t = '<input type="text" placeholder="0.00" onfocus ="showAutoPrices(this)" class="textbox goodsAuto" value="' + value + '" ><span class="ui-icon-triangle-1-s"></span>';
                return t;
            }

            /**
             * 自定义折后价编辑生成函数
             * @param value
             * @param options
             * @returns {string}
             */
            function truePriceElement(value, options) {
                var t = '<input type="text" placeholder="0.00" onfocus ="showAutoTruePrices(this)" class="textbox goodsAuto" value="' + value + '" ><span class="ui-icon-triangle-1-s"></span>';
                return t;
            }


            /**
             * 自定义商品选择好后返回表格的值
             * @param elem
             * @param operation
             * @param value
             * @returns {*|$}
             */
            function goodsValue(elem, operation, value) {
                if (operation === 'get') {

                    return $(elem).val();
                } else if (operation === 'set') {
                    $(elem).val(value);
                }
            }

            /**
             * 自定义尺码选择好后返回到表格的值
             * @param elem
             * @param operation
             * @param value
             * @returns {*|$}
             */
            function sizeValue(elem, operation, value) {
                if (operation === 'get') {

                    return $(elem).val();
                } else if (operation === 'set') {
                    $(elem).val(value);
                }
            }

            /**
             * 自定义颜色选择好后返回到表格的值
             * @param elem
             * @param operation
             * @param value
             * @returns {*|$}
             */
            function colorValue(elem, operation, value) {
                if (operation === 'get') {

                    return $(elem).val();
                } else if (operation === 'set') {
                    $(elem).val(value);
                }
            }

            /**
             * 自定义单位选择好后返回到表格的值
             * @param elem
             * @param operation
             * @param value
             * @returns {*|$}
             */
            function priceValue(elem, operation, value) {
                if (operation === 'get') {
                    var returnValue = "";
                    if ($(elem).val() || $(elem).val() === 0) {
                        returnValue = $(elem).val();
                    }
                    hideAutoPrices();
                    return returnValue;
                } else if (operation === 'set') {
                    $(elem).val(value);
                }
            }

            /**
             * 自定义单位选择好后返回到表格的值
             * @param elem
             * @param operation
             * @param value
             * @returns {*|$}
             */
            function truePriceValue(elem, operation, value) {
                if (operation === 'get') {
                    var returnValue = "";
                    if ($(elem).val() || $(elem).val() === 0) {
                        returnValue = $(elem).val();
                    }
                    hideAutoTruePrices();
                    return returnValue;
                } else if (operation === 'set') {
                    $(elem).val(value);
                }
            }

            /**
             * 点击单元格开始进行编辑事件
             * @param rowid
             * @param cellname
             * @param value
             * @param iRow
             * @param iCol
             */
            function beforeEditCell(rowid, cellname, value, iRow, iCol) {
                //全局变量，记录准备编辑的行
                lastrow = iRow;
                //全局变量，记录准备编辑的列
                lastcell = iCol;

                getScope('OrderCtrl').$apply(function (scope) {
                    scope.showAutoGoods = false;
                    scope.showAutoSize = false;
                    scope.showAutoColor = false;
                    scope.showAutoPrice = false;
                    scope.showAutoTruePrice = false;
                });
            }

            function afterEditCell(rowid, cellname, value, iRow, iCol) {
                setTimeout(function () {
                    $("#" + iRow + "_" + cellname).focus().val(value);
                });
                //$("#"+iRow+"_"+cellname).focus();                     //聚焦被覆盖，这个地方需要修改
                //$(".textbox.goodsAuto.customelement")[0].focus();     //聚焦被覆盖，这个地方需要修改

            }

            function beforeSaveCell(rowid, cellname, value, iRow, iCol) {
                /*calcTotal('amount');
                calcTotal('trueAmount');*/
            }

            function afterRestoreCell(rowid, value, iRow, iCol) {

                var ctrlScope = getScope('OrderCtrl');


                setTimeout(function () {
                    ctrlScope.$apply(function (scope) {
                        scope.showAutoGoods = false;
                        scope.showAutoSize = false;
                        scope.showAutoColor = false;
                        scope.showAutoPrice = false;
                        scope.showAutoTruePrice = false;
                    });
                });
            }

            /**
             * 在每个表格调用之后事件函数，进行自动填充，金额计算等工作
             * @param rowid
             * @param cellname
             * @param value
             * @param iRow
             * @param iCol
             */
            function afterSaveCell(rowid, cellname, value, iRow, iCol) {
                var scope = getScope('OrderCtrl');
                scope.notSaveOrder = true;
                var currentRowData = $("#purchaseList").jqGrid("getRowData", rowid);
                if (cellname == "goodName") {
                    // temp =  scope.curEditGoodInput.val();
                    var good = scope.selGood;
                    if (good == undefined) {
                        $("#purchaseList").setRowData(rowid, {
                            goodName: "",
                            sizeName: "",
                            colorName: "",
                            goods_no: "",
                            price: "",
                            amount: "",
                            trueAmount: ""
                        });
                        return;
                    }
                    var discount = currentRowData['discount'];

                    $("#purchaseList").setRowData(rowid, {
                        quantity: 1,
                        price: good.market_price,
                        truePrice: setScale(accDiv(accMul(good.market_price, discount), 100), 2),
                        amount: good.market_price,
                        trueAmount: setScale(accDiv(accMul(good.market_price, discount), 100), 2),
                        sizeIds: good.sizeIds,
                        colorIds: good.colorIds,
                        goods_no: good.goods_no,
                        discount: discount
                    });


                    scope.selGood = undefined;
                    //  $("#purchaseList").setRowData( rowid, { unit:1, quantity:1,price:1,amount:1 });
                } else if (cellname == "sizeName") {

                    var rowIds = $("#purchaseList").jqGrid('getDataIDs'); //获取所有行Id
                    var existsSameFlag = false;
                    for (var j = 0; j < rowIds.length; j++) {
                        var thisRow = $("#purchaseList").jqGrid("getRowData", rowIds[j]); //当前行数据
                        if (thisRow['goods_no'] == currentRowData['goods_no'] && thisRow['colorId'] == currentRowData['colorId'] && thisRow['sizeId'] == scope.selSize.id) {
                            if (thisRow['id'] == rowid) {
                                continue;
                            } else {
                                var r = confirm("已经存在相同颜色尺码的商品，是否合并数量为一条记录？");
                                if (r) {
                                    $("#purchaseList").setRowData(rowIds[j], {
                                        packetCount: parseInt(thisRow['packetCount']) + parseInt(currentRowData['packetCount']),
                                        packetNumber: parseInt(thisRow['packetNumber']),
                                        quantity: accMul(parseInt(thisRow['packetCount']), currentRowData['packetNumber']) + parseInt(currentRowData['quantity']),
                                        amount: accMul((accMul(parseInt(thisRow['packetCount']), currentRowData['packetNumber']) + parseInt(currentRowData['quantity'])), thisRow['price']),
                                        trueAmount: accMul((accMul(parseInt(thisRow['packetCount']), currentRowData['packetNumber']) + parseInt(currentRowData['quantity'])), thisRow['truePrice'])
                                    });
                                    $("#purchaseList").jqGrid("delRowData", rowid);
                                } else {
                                    $("#purchaseList").setRowData(rowid, {sizeId: '', sizeName: '', number: ''});
                                }

                                existsSameFlag = true;
                                break;
                            }
                        }
                    }

                    if (!existsSameFlag) {
                        $("#purchaseList").setRowData(rowid, {sizeId: scope.selSize.id});
                        currentRowData.sizeId = scope.selSize.id;
                        scope.updateRowDataForChangeSku(rowid, currentRowData);
                        scope.setGoodsStoredCount();
                    }
                } else if (cellname == "colorName") {
                    if (scope.selColor != undefined) {
                        var rowIds = $("#purchaseList").jqGrid('getDataIDs'); //获取所有行Id
                        var existsSameFlag = false;
                        for (var j = 0; j < rowIds.length; j++) {
                            var thisRow = $("#purchaseList").jqGrid("getRowData", rowIds[j]); //当前行数据
                            if (thisRow['goods_no'] == currentRowData['goods_no'] && thisRow['colorId'] == scope.selColor.id && thisRow['sizeId'] == currentRowData['sizeId']) {
                                if (thisRow['id'] == rowid) {
                                    continue;
                                } else {
                                    var r = confirm("已经存在相同颜色尺码的商品，是否合并数量为一条记录？");
                                    if (r) {
                                        $("#purchaseList").setRowData(rowIds[j], {
                                            packetCount: parseInt(thisRow['packetCount']) + parseInt(currentRowData['packetCount']),
                                            packetNumber: parseInt(thisRow['packetNumber']),
                                            quantity: accMul(parseInt(thisRow['packetCount']), currentRowData['packetNumber']) + parseInt(currentRowData['quantity']),
                                            amount: accMul((accMul(parseInt(thisRow['packetCount']), currentRowData['packetNumber']) + parseInt(currentRowData['quantity'])), thisRow['price']),
                                            trueAmount: accMul((accMul(parseInt(thisRow['packetCount']), currentRowData['packetNumber']) + parseInt(currentRowData['quantity'])), thisRow['truePrice'])
                                        });
                                        $("#purchaseList").jqGrid("delRowData", rowid);
                                    } else {
                                        $("#purchaseList").setRowData(rowid, {colorId: '', colorName: '', number: ''});
                                    }
                                    ;
                                    existsSameFlag = true;
                                    break;
                                }
                            }
                        }
                        if (!existsSameFlag) {
                            $("#purchaseList").setRowData(rowid, {colorId: scope.selColor.id});
                            currentRowData.colorId = scope.selColor.id;
                            scope.updateRowDataForChangeSku(rowid, currentRowData);
                            scope.setGoodsStoredCount();
                        }
                    }
                } else if (cellname == "packetCount") {
                    if (value < 1) {
                        value = 1;
                        $("#purchaseList").setRowData(rowid, {quantity: 1});
                    }

                    /*if(parseInt(rowData['number']) - parseInt(value) < 0 ){
                        alert("请注意：该类商品库存不足！");
                    }*/

                    $("#purchaseList").setRowData(rowid, {
                        amount: accMul(accMul(currentRowData['packetNumber'], value), currentRowData['price']),
                        trueAmount: accMul(accMul(currentRowData['packetNumber'], value), currentRowData['truePrice']),
                        quantity: accMul(currentRowData['packetNumber'], value)
                    });
                } else if (cellname == "price") {
                    $("#purchaseList").setRowData(rowid, {truePrice: setScale(accDiv(accMul(currentRowData['price'], currentRowData['discount']), 100), 2)});
                    $("#purchaseList").setRowData(rowid, {
                        amount: accMul(currentRowData['quantity'], currentRowData['price']),
                        trueAmount: accMul(setScale(accDiv(accMul(currentRowData['price'], currentRowData['discount']), 100), 2), currentRowData['quantity'])
                    });
                } else if (cellname == "discount") {
                    if (value < 0) {
                        value = 100;
                        $("#purchaseList").setRowData(rowid, {discount: 100});
                    }
                    $("#purchaseList").setRowData(rowid, {truePrice: setScale(accDiv(accMul(currentRowData['price'], currentRowData['discount']), 100), 2)});
                    $("#purchaseList").setRowData(rowid, {trueAmount: accMul(currentRowData['quantity'], setScale(accDiv(accMul(currentRowData['price'], currentRowData['discount']), 100), 2))});
                } else if (cellname = "truePrice") {
                    if (currentRowData['price'] == 0) {
                        $("#purchaseList").setRowData(rowid, {discount: 100});
                        value = 0;
                    } else {
                        $("#purchaseList").setRowData(rowid, {discount: setScale(accDiv(accMul(currentRowData['truePrice'], 100), currentRowData['price']), 2)});
                    }
                    $("#purchaseList").setRowData(rowid, {trueAmount: accMul(currentRowData['truePrice'], currentRowData['quantity'])});
                }

                //更新合计行上的合计指标
                updateTotalNumbers();

                setTimeout(function () {
                    scope.$apply(function (scope) {
                        if (scope.businessConfig.zeroPaid == 1) {
                            scope.order.alreadyPaid = 0;
                        } else {
                            scope.order.alreadyPaid = scope.order.finalTotalAmount;
                        }
                    });
                });
            }

            $("#purchaseList").jqGrid(
                {
                    cmTemplate: {sortable: false},
                    datatype: "local",
                    cellEdit: true,
                    cellsubmit: 'clientArray',
                    colModel: [
                        {
                            name: 'operate',
                            index: 'operate',
                            label: "操作",
                            formatter: pubBillsOper,
                            align: "center",
                            width: 70,
                            fixed: true,
                            resizable: false
                        },
                        {
                            hidden: true,
                            name: 'id',
                            index: 'id'
                        }, {
                            hidden: true,
                            name: 'sizeIds',
                            index: 'sizeIds',
                            label: "商品尺码串"
                        }, {
                            hidden: true,
                            name: 'sizeId',
                            index: 'sizeId',
                            label: "商品尺码"
                        }, {
                            hidden: true,
                            name: 'colorIds',
                            index: 'colorIds',
                            label: "颜色串"
                        }, {
                            hidden: true,
                            name: 'colorId',
                            index: 'colorId',
                            label: "颜色串"
                        }, {
                            hidden: true,
                            name: 'goods_id',
                            index: 'goods_id'
                        }, {
                            name: 'goodName',
                            index: 'goodName',
                            label: "商品",
                            sortable: true,
                            formatter: editableColumnTip,
                            unformat: editableColumnRemoveTip,
                            width: 300,
                            classes: "ui-ellipsis",
                            editable: true,
                            edittype: "custom",
                            editrules: {required: false},
                            editoptions: {
                                custom_element: goodElement,
                                custom_value: goodsValue,
                                trigger: "ui-icon-ellipsis"
                            }
                        }, {
                            hidden: true,
                            name: 'name',
                            index: 'name',
                            label: "名称"
                        }, {
                            name: 'goods_no',
                            index: 'goods_no',
                            label: "货号",
                            sortable: true
                        }, {
                            name: 'barCode',
                            index: 'barCode',
                            label: "条码",
                            align: "center",
                            width: 190
                        },
                        {
                            name: 'colorName',
                            index: 'colorName',
                            label: "颜色",
                            align: "center",
                            sortable: true,
                            classes: "ui-ellipsis cell-can-edit",
                            editable: true,
                            edittype: "custom",
                            editoptions: {custom_element: colorElement, custom_value: colorValue}
                        }, {
                            name: 'sizeName',
                            index: 'sizeName',
                            label: "尺码",
                            align: "center",
                            classes: "ui-ellipsis cell-can-edit",
                            editable: true,
                            edittype: "custom",
                            editoptions: {
                                custom_element: sizeElement,
                                custom_value: sizeValue,
                                trigger: "ui-icon-ellipsis"
                            }
                        }, {
                            name: 'quantity',
                            index: 'quantity',
                            hidden: true
                        }, {
                            name: 'packetCount',
                            index: 'packetCount',
                            label: "数量",
                            align: "right",
                            width: 155,
                            editable: true,
                            formatter: 'integer',
                            classes: "ui-ellipsis cell-can-edit",
                            editrules: {
                                custom: true,
                                custom_func: function (value) {
                                    var packetCount = parseInt(value);
                                    var isValid = !isNaN(packetCount);
                                    var isInteger = value % 1 == 0;
                                    if (!isValid || !isInteger) {
                                        return [false, '请输入有效整数'];
                                    }
                                    if (packetCount == 0) {
                                        return [false, '商品数量不能为0'];
                                    }
                                    return [true, ''];
                                }
                            },
                            editoptions: {
                                dataEvents: [
                                    {
                                        type: 'focus', fn: function (e) {
                                            setTimeout(function () {
                                                $(e.target).select();
                                            }, 50);
                                        }
                                    }
                                ]
                            }
                        }, {
                            name: 'packetNumber',
                            index: 'packetNumber',
                            label: "量",
                            align: "left",
                            width: 45,
                            hidden: true,
                            formatter: function (val, opt, row) {
                                if (val == 1 || !val) {
                                    return '';
                                }
                                return '×' + val;
                            },
                            unformat: function (val, opt, row) {
                                if (!val) {
                                    return 1;
                                }
                                return parseInt(val.substring(1));
                            }
                        }, {
                            name: 'price',
                            index: 'price',
                            align: "right",
                            label: "单价", sorttype: "float", formatter: 'currency',
                            editable: true,
                            editrules: {minValue: 0, number: true},
                            classes: "ui-ellipsis cell-can-edit", edittype: "custom",
                            editoptions: {
                                custom_element: priceElement, custom_value: priceValue,
                                dataEvents: [
                                    {
                                        type: 'focus', fn: function (e) {
                                            setTimeout(function () {
                                                $(e.target).select();
                                            }, 50);
                                        }
                                    }
                                ]
                            }
                        }, {
                            name: 'discount',
                            index: 'discount',
                            label: "折扣(%)",
                            editable: true,
                            classes: "ui-ellipsis cell-can-edit",
                            align: "right",
                            defaultValue: 100,
                            formatter: discount,
                            editrules: {minValue: 0, number: true},
                            editoptions: {
                                dataEvents: [
                                    {
                                        type: 'focus', fn: function (e) {
                                            setTimeout(function () {
                                                $(e.target).select();
                                            }, 50);
                                        }
                                    }
                                ]
                            }
                        }, {
                            name: 'truePrice',
                            index: 'truePrice',
                            align: "right",
                            label: "折后价", sorttype: "float", formatter: 'currency',
                            editable: true,
                            editrules: {minValue: 0, number: true},
                            classes: "ui-ellipsis cell-can-edit", edittype: "custom",
                            editoptions: {
                                custom_element: truePriceElement, custom_value: truePriceValue,
                                dataEvents: [
                                    {
                                        type: 'focus', fn: function (e) {
                                            setTimeout(function () {
                                                $(e.target).select();
                                            }, 50);
                                        }
                                    }
                                ]
                            }
                        }, {
                            name: 'market_price',
                            index: 'market_price',
                            hidden: true,
                            label: "采购价"
                        }, {
                            name: 'supplierPrice',
                            index: 'supplierPrice',
                            hidden: true,
                            label: "供应商上次价格"
                        }, {
                            name: 'supplierTruePrice',
                            index: 'supplierTruePrice',
                            hidden: true,
                            label: "供应商上次折后价格"
                        }, {
                            hidden: true,
                            name: 'number',
                            index: 'number',
                            label: "当前数量",
                            align: "right",
                            formatter: 'integer'
                        }, {
                            hidden: true,
                            name: 'amount',
                            index: 'amount',
                            label: "金额",
                            align: "right",
                            sorttype: "float", formatter: 'currency'
                        }, {
                            name: 'trueAmount',
                            index: 'trueAmount',
                            label: "金额",
                            align: "right",
                            sorttype: "float", formatter: 'currency'
                        }, {
                            hidden: true,
                            name: 'currentSku',
                            index: 'currentSku',
                            label: "商品sku",
                        }],
                    multiSort: true,
                    //是否在表格最前端添加1列为自动编号
                    rownumbers: true,
                    rownumWidth: 35,
                    //一页显示几行？
                    rowNum: 1000,
                    //从弟几页开始
                    page: 1,
                    //多少页一段
                    rowlist: [10, 20, 30],
                    height: "100%",
                    width: "100%",
                    footerrow: true,
                    autowidth: true,
                    afterSaveCell: afterSaveCell,
                    beforeEditCell: beforeEditCell,
                    afterEditCell: afterEditCell,
                    beforeSaveCell: beforeSaveCell,
                    afterRestoreCell: afterRestoreCell,
                    oneditfunc: function () {
                        // alert ("edited");
                    },
                    loadComplete: function () {
                        //更新合计行上的合计指标
                        updateTotalNumbers();
                    }
                    , loadGrid: function (t) {
                        function e(t) {

                        }
                    }

                }).jqGrid('navGrid', "#pager", {
                refresh: true,
                add: true,
                edit: true,
                del: true,
                search: false,
                sortable: false
            }, {
                closeOnEscape: true,
                closeAfterEdit: true
            }, {
                closeOnEscape: true,
                closeAfterAdd: true,
                serializeEditData: function (data) {
                    return $.param($.extend({}, data, {
                        id: ''
                    }));
                }
            });
            $("#purchaseList").trigger("reloadGrid");


            for (var i = 0; i <= 5; i++) {
                addNewEmptyRow();

            }

            //修复排序列表头样式
            var myGrid = $("#purchaseList");
            var cm = myGrid[0].p.colModel;
            $.each(myGrid[0].grid.headers, function (index, value) {
                var cmi = cm[index], colName = cmi.name;
                if (cmi.sortable && colName !== 'rn' && colName !== 'cb' && colName !== 'subgrid') {
                    $('div.ui-jqgrid-sortable', value.el).addClass('sortable');
                    $('div.ui-jqgrid-sortable', value.el).prepend('<span class="sortable-icon"></span>');
                }
            });

            //自适应宽度
            $(window).resize(function () {
                //在resize过程中宽度为0时不应设置
                if ($("#purchaseList").parent().parent().parent().parent().parent().width() != 0) {
                    $("#purchaseList").setGridWidth($("#purchaseList").parent().parent().parent().parent().parent().width());
                }
                $("#listGrid").setGridWidth($("#listGrid").parent().parent().parent().parent().parent().width());
            });

            //初始化二维录入弹框
            $("#twoDisDiv").dialog({
                autoOpen: false,
                show: {
                    effect: "blind",
                    duration: 10
                },
                minWidth: 800,
                modal: true

            });


            //判断是否加载订单
            /*if (onLoadOrdersSn != null && onLoadOrdersSn != undefined && onLoadOrdersSn != '') {
                getScope('OrderCtrl').loadOneOrder(onLoadOrdersSn);
            }*/
            // 销售单转采购单
            /*getWholesaleOrders(wholesaleOrdersSn);*/

            //leavePage([{test: "getScope('OrderCtrl').notSaveOrder", info: "亲，单据还没有保存哦！"}]);

            //$(window).resize();
        });

    /**
     *   添加空的新行
     * @param position   插入的位置（first：表格顶端；last：表格底端；before：srcrowid之前；after：srcrowid之后）；
     * @param srcrowid   新行将插入到srcrowid指定行的前面或后面
     * @returns {number}返回新rowId
     */
    function addNewEmptyRow(position, srcrowid) {
        if (maxRowId == undefined) {
            maxRowId = $("#purchaseList").jqGrid('getDataIDs').length;
        }
        maxRowId = maxRowId + 1;
        var data = {
            id: maxRowId,
            goodName: "",
            goods_id: "",
            colorName: "",
            sizeName: "",
            price: "",
            quantity: 1,
            packetCount: 1,
            packetNumber: 1,
            number: "",
            amount: "",
            trueAmount: "",
            discount: getScope('OrderCtrl').supplierDiscount
        };
        $('#purchaseList').jqGrid('addRowData', maxRowId, data, position, srcrowid);
        return maxRowId;
    }

    /**
     * 监听表格中的键盘事件
     */
    $(document).delegate('.ui-jqgrid', 'keydown', function (event) {
        var key = event.charCode || event.keyCode;
        if (key == 9) {
            var selRowId = $('#purchaseList').jqGrid('getGridParam', 'selrow');
            var arrIds = $("#purchaseList").jqGrid('getDataIDs');

            if (selRowId == arrIds[arrIds.length - 1]) {
                var newRowId = addNewEmptyRow();
                $('#purchaseList').editCell(newRowId, 8, true);      //设置最新行被选中
            }

        }

    });

    /**
     * 在当前行下插入空行
     * @param rowId
     */
    function insertEmptyRow(event, srcRowId) {
        stopEvent(event);

        $("#purchaseList").jqGrid("saveCell", lastrow, lastcell);
        //设置最新行被选中
        // $('#purchaseList').editCell( lastrow,lastcell, false);
        $('#purchaseList').jqGrid('resetSelection');
        //   $("#purchaseList").saveRow(lastrow);

        var newRowId = addNewEmptyRow('after', srcRowId);

        //var newRowId = addNewEmptyRow('after',3);
        var iRow = $('#' + $.jgrid.jqID(newRowId))[0].rowIndex;
        $('#purchaseList').editCell(iRow, 8, true);      //设置最新行被选中
        //$( "#purchaseList" ).resetSelection();
    };

    function delRow(event, rowId) {
        stopEvent(event);
        if ($("#purchaseList").jqGrid("getRowData").length == 1) { //只剩一行时，不允许删除
            return;
        }
        if ($("#purchaseList").getRowData(rowId).goodName) {
            getScope('OrderCtrl').notSaveOrder = true;
        }
        $("#purchaseList").jqGrid("saveCell", lastrow, lastcell);

        var currentRowData = $('#purchaseList').jqGrid('getRowData', rowId);
        var flag = false;
        $("#purchaseList").jqGrid("delRowData", rowId);
        var allRows = $("#purchaseList").jqGrid("getRowData");
        for (var i = 0; i < allRows.length; i++) {
            if (currentRowData['goods_no'] == allRows[i]['goods_no']) {
                flag = true;
                break;
            }
        }
        if (!flag) {
            for (var i = 0; i < getScope('OrderCtrl').snPacketArr.length; i++) {
                //只循环一次
                for (var snPacket in getScope('OrderCtrl').snPacketArr[i]) {
                    if (snPacket == currentRowData['goods_no']) {
                        getScope('OrderCtrl').snPacketArr.splice(i, 1);
                    }
                }
            }
        }
        //更新合计行上的合计指标
        updateTotalNumbers();

        setTimeout(function () {
            getScope('OrderCtrl').$apply(function (scope) {
                if (scope.businessConfig.zeroPaid == 1) {
                    scope.order.alreadyPaid = 0;
                } else {
                    scope.order.alreadyPaid = scope.order.finalTotalAmount;
                }
            });
        });
    }

    /**
     * 合计商品列表中某些列的数值，不包括货号列为空的行
     * @returns 返回包括各个传入列合计值的对象，如{totalAvailableRows:120,quatity:98,amount:102},其中totalAvailableRows为内置变量，用以表示商品不为空的行数
     *
     */
    function calcTotal() {
        var allRowData = $("#purchaseList").jqGrid("getRowData");

        var result = {};
        for (var i = 0; i < arguments.length; i++) {
            result[arguments[i]] = 0;
        }

        result['totalAvailableRows'] = 0;
        for (var i = 0; i < allRowData.length; i++) {
            var currentRowData = allRowData[i];
            if (currentRowData['goodName']) {
                for (var j = 0; j < arguments.length; j++) {
                    result[arguments[j]] = accAdd(result[arguments[j]], currentRowData[arguments[j]]);
                }

                result['totalAvailableRows'] = result['totalAvailableRows'] + 1;
            }
        }
        return result;
    }

    /**
     * 更新商品单据的合计值
     */
    function updateTotalNumbers() {
        //更新合计行上的合计指标
        var totalObj = calcTotal('quantity', 'amount', 'trueAmount');
        $("#purchaseList").footerData("set", $.extend({goodName: "合计", packetCount: totalObj.quantity}, totalObj));

        //更新应收合计等合计指标
        var scope = getScope('OrderCtrl');
        scope.order.quantity = totalObj.quantity;
        scope.order.totalAmount = totalObj.amount;
        scope.order.trueTotalAmount = totalObj.trueAmount;
        scope.order.finalTotalAmount = accAdd(accSub(scope.order.trueTotalAmount, scope.order.wipeZero), scope.order.otherCost);
        scope.order.totalAvailableRows = totalObj.totalAvailableRows;

    }

    /**
     * 点击商品列时，如果输入为空，显示商品下拉框
     * @param obj
     */
    function loadGoodsFirst(obj) {
        getScope("OrderCtrl").barCodeFocus = false;
        if ($(obj).val() == '') {
            var ctrl = angular.element(document.getElementById('OrderCtrl'));
            var ctrlScope = ctrl.scope();
            ctrlScope.$apply(function (scope) {
                //重新加载商品并显示下拉框
                scope.changAutoGoods(obj);
                //商品查询下拉选中项
                scope.searchGoodAct = -1;
            });
        }
        setTimeout(function () {
            obj.select();
        }, 50);
    }

    // 500毫秒后查询匹配的商品
    var vCheckGoodsTimeOut = undefined;

    /**
     * 显示商品下拉框
     * @param obj
     */
    function changAutoGoods(obj) {
        var ctrl = angular.element(document.getElementById('OrderCtrl'));
        var ctrlScope = ctrl.scope();
        if (vCheckGoodsTimeOut) {
            window.clearTimeout(vCheckGoodsTimeOut);
        }
        // 500毫秒内如果有改动查询关键字，就取消查询，否则触发查询。
        vCheckGoodsTimeOut = setTimeout(function () {
            ctrlScope.$apply(function (scope) {
                //重新加载商品并显示下拉框
                scope.changAutoGoods(obj);
                //商品查询下拉选中项
                scope.searchGoodAct = -1;
            });
        }, 500);
    }

    /**
     * 显示商品下拉框,兼容IE(ie9商品输入框中删除输入字符时不会触发onpropertychange事件)
     * @param obj
     */
    function changAutoGoodsIE(event) {
        if (event.propertyName.toLowerCase() == "value") {
            var ctrl = angular.element(document.getElementById('OrderCtrl'));
            var ctrlScope = ctrl.scope();
            var vElement = event.srcElement;
            if (vCheckGoodsTimeOut) {
                window.clearTimeout(vCheckGoodsTimeOut);
            }
            // 500毫秒内如果有改动查询关键字，就取消查询，否则触发查询。
            vCheckGoodsTimeOut = window.setTimeout(function () {
                ctrlScope.$apply(function (scope) {
                    scope.changAutoGoods(vElement);  //重新加载商品并显示下拉框
                    scope.searchGoodAct = -1; //商品查询下拉选中项
                });
            }, 500);
        }
    }

    /**
     * 商品查询中按下键盘事件
     */
    function goodsSearchPress(keyEvent, obj) {
        getScope('OrderCtrl').rowId = $(obj).parent().parent().parent().attr("id"); //当前行id
        var keyCode = keyEvent.which;

        switch (keyCode) {

            case 38: //up
                goodsSearchCtrlUp(keyEvent);
                break;
            case 40: //down
                goodsSearchCtrlDown(keyEvent);
                break;
            case 13: //Enter
                goodsSearchCtrlEnter(keyEvent);
                break;
            default:

        }

    }

    /**
     * 处理商品查询中按下键盘事件,向上键
     */
    function goodsSearchCtrlUp(keyEvent) {
        getScope('OrderCtrl').$apply(function (scope) {
            if (scope.searchGoodAct > 0) {
                scope.searchGoodAct--; //当前行id
            }

        });
    }

    /**
     * 处理商品查询中按下键盘事件,向下键
     */
    function goodsSearchCtrlDown(keyEvent) {
        getScope('OrderCtrl').$apply(function (scope) {
            if (scope.searchGoodAct < scope.goods.length - 1) {
                scope.searchGoodAct++; //当前行id
            }
        });
    }

    /**
     * 处理商品查询中按下键盘事件,Enter键
     */
    function goodsSearchCtrlEnter(keyEvent) {
        getScope('OrderCtrl').$apply(function (scope) {
            if (scope.searchGoodAct > -1 && scope.searchGoodAct < scope.goods.length) {
                scope.selAutoGood(scope.goods[scope.searchGoodAct]);
                scope.searchGoodAct = -1;//处理完后初始化为-1
            }
        });
    }

    /**
     * 处理并显示二维录入框，点输入框内单品后三个点(详情)触发
     * 直接重新搜索商品不会触发此处
     */
    function showTwoDimensionSel(obj) {
        getScope('OrderCtrl').$apply(function (scope) {
            scope.rowId = $(obj).parent().parent().parent().attr("id"); //当前行id

            scope.currentRowData = $('#purchaseList').jqGrid('getRowData', scope.rowId); //行数据
            scope.initPacketNumber(scope.currentRowData.goods_no, scope.currentRowData.packetNumber);
            scope.showAndProTwoDimensionSel(scope.currentRowData);
        });
    }

    /**
     * 显示尺码的下拉框
     * @param obj
     */
    function showAutoSizes(obj) {

        getScope('OrderCtrl').$apply(function (scope) {
            scope.currentSizes = [];   //当前商品所拥有的尺码
            scope.rowId = $(obj).parent().parent().parent().attr("id"); //当前行id
            var rowData = $('#purchaseList').jqGrid('getRowData', scope.rowId); //行数据

            var curGoodSn = rowData['goods_no']; //行货号
            if (curGoodSn == undefined || curGoodSn == "") {
                return;
            }
            scope.currentSizes = idStringToObjectArray(scope.allSizes, rowData['sizeIds'], 'id', ',');

            scope.showAutoSize = true;

            var offset = $(obj).offset();
            var top = (offset.top + $(obj).outerHeight() - 127) + 'px';
            var width = ($(obj).width() + 18) + 'px';
            var left = (offset.left - 210) + 'px';
            scope.autoSizStyle = {top: top, width: width, left: left};
            scope.curEditSizeInput = $(obj);       //指向当前编辑的表格
        });
    }

    /**
     * 显示颜色的下拉框
     * @param obj
     */
    function showAutoColors(obj) {
        getScope('OrderCtrl').$apply(function (scope) {
            scope.currentSizes = [];   //当前商品所拥有的尺码
            scope.rowId = $(obj).parent().parent().parent().attr("id"); //当前行id
            var rowData = $('#purchaseList').jqGrid('getRowData', scope.rowId); //行数据

            var curGoodSn = rowData['goods_no']; //行货号
            if (curGoodSn == undefined || curGoodSn == "") {
                return;
            }
            scope.currentColors = idStringToObjectArray(scope.allColors, rowData['colorIds'], 'id', ',');

            scope.showAutoColor = true;
            var offset = $(obj).offset();
            var top = (offset.top + $(obj).outerHeight() - 127) + 'px';
            var width = ($(obj).width() + 18) + 'px';
            var left = (offset.left - 210) + 'px';
            scope.autoColorStyle = {top: top, width: width, left: left};

            scope.curEditColorInput = $(obj);       //指向当前编辑的表格
        });
    }


    /**
     * 显示单价的下拉框
     * @param obj
     */
    function showAutoPrices(obj) {
        getScope('OrderCtrl').$apply(function (scope) {
            scope.rowId = $(obj).parent().parent().parent().attr("id"); //当前行id
            var rowData = $('#purchaseList').jqGrid('getRowData', scope.rowId); //行数据
            scope.currentPrices = [];

            if (rowData['market_price'] || rowData['market_price'] === 0) {
                scope.currentPrices.push({text: '采购价', value: setScaleToFixed(rowData['market_price'], 2)});
            }

            if (rowData['supplierPrice'] || rowData['supplierPrice'] === 0) {
                scope.currentPrices.push({text: '上次单价', value: setScaleToFixed(rowData['supplierPrice'], 2)});
            }

            if (scope.currentPrices.length > 0) {
                scope.showAutoPrice = true;
                var offset = $(obj).offset();
                var top = (offset.top + $(obj).outerHeight()) + 'px';
                var width = ($(obj).width() + 18) + 'px';
                var left = (offset.left) + 'px';
                scope.autoPriceStyle = {top: top, 'min-width': width, left: left};
                //指向当前编辑的表格
                scope.curEditPriceInput = $(obj);
            }
        });
        setTimeout(function () {
            obj.select();
        }, 50);
    }

    /**
     * 关闭单价的下拉框
     */
    function hideAutoPrices() {
        getScope('OrderCtrl').$apply(function (scope) {
            scope.showAutoPrice = false;
        });
    }

    /**
     * 显示折后价的下拉框
     * @param obj
     */
    function showAutoTruePrices(obj) {
        getScope('OrderCtrl').$apply(function (scope) {
            scope.rowId = $(obj).parent().parent().parent().attr("id"); //当前行id
            var rowData = $('#purchaseList').jqGrid('getRowData', scope.rowId); //行数据

            scope.currentTruePrices = [];
            if (rowData['supplierTruePrice'] || rowData['supplierTruePrice'] === 0) {
                scope.currentTruePrices.push({text: '上次折后价', value: setScaleToFixed(rowData['supplierTruePrice'], 2)});
            }

            if (scope.currentTruePrices.length > 0) {
                scope.showAutoTruePrice = true;
                var offset = $(obj).offset();
                var top = (offset.top + $(obj).outerHeight()) + 'px';
                var width = ($(obj).width() + 18) + 'px';
                var left = (offset.left) + 'px';
                scope.autoTruePriceStyle = {top: top, 'min-width': width, left: left};

                scope.curEditTruePriceInput = $(obj);       //指向当前编辑的表格
            }
        });
        setTimeout(function () {
            obj.select();
        }, 50);
    };

    /**
     * 关闭折后价的下拉框
     */
    function hideAutoTruePrices() {
        getScope('OrderCtrl').$apply(function (scope) {
            scope.showAutoTruePrice = false;
        });
    }

    /**
     *   点击表格之外
     * @param e
     */
    var lastrow;
    var lastcell;
    $('html').bind('click', function (e) { //用于点击其他地方保存正在编辑状态下的行
        if (lastrow != "" && lastcell != "") { //if a row is selected for edit
            if ($(e.target).closest('#purchaseList').length == 0) { //and the click is outside of the grid //save the row being edited and unselect the row
                // alert(lastsel);$('#purchaseList').jqGrid('restoreRow', lastsel);
                // $('#purchaseList').resetSelection();
                //$("#purchaseList").jqGrid("restoreCell",lastrow,lastcell);

                var ctrl = angular.element(document.getElementById('OrderCtrl'));
                var ctrlScope = ctrl.scope();
                ctrlScope.$apply(function (scope) {
                    scope.showAutoGoods = false;
                    scope.showAutoSize = false;
                    scope.showAutoColor = false;
                    scope.showAutoPrice = false;
                    scope.showAutoTruePrice = false;
                });
                $("#purchaseList").jqGrid("saveCell", lastrow, lastcell);
                lastrow = "";
                lastcell = "";
                setTimeout(function () {
                    $(e.target).focus();
                }, 50); //由于保存表格语句会造成所点击的input失焦，所以需要臭不重新聚焦（需要重构）
            }
        }

    });

    /*回车事件*/
    $('#searchForm').keypress(function (e) {
        if (e.keyCode == '13') {
            stopEvent(e);
            $('#searchBtn').click();
        }
    });

    function getWholesaleOrders(wholesaleOrdersSn) {
        if (wholesaleOrdersSn) {
            var scope = getScope('OrderCtrl');
            scope.notSaveOrder = true;
            $.ajax({
                    url: base + '/admin/inner/sale/toPurchaseOrderPage.ac?ordersSn=' + wholesaleOrdersSn,
                    type: 'GET',
                    headers: {
                        Accept: "application/json; charset=utf-8"
                    },
                    beforeSend: function () {
                        scope.loadingTips = "加载中……";
                        scope.loadingOrder = true;
                    },
                    success: function (result) {
                        var purchaseOrder = result;
                        if (purchaseOrder.statusCode != 1) {
                            alert(purchaseOrder.content);
                            scope.loadingOrder = false;
                            return;
                        }
                        scope.editForm.$setPristine();//清除当前状态
                        if (purchaseOrder.object.order) {
                            if (purchaseOrder.object.order.depotId) {
                                scope.order.depot = {
                                    val: purchaseOrder.object.order.depotId,
                                    text: purchaseOrder.object.order.depotName
                                };
                                scope.order.depotId = purchaseOrder.object.order.depotId;
                                scope.order.depotName = purchaseOrder.object.order.depotName;
                            }
                            if (purchaseOrder.object.order.accountId) {
                                scope.selAccount = {
                                    val: purchaseOrder.object.order.accountId,
                                    text: purchaseOrder.object.order.accountName
                                };
                                scope.order.accountId = purchaseOrder.object.order.accountId;
                            }
                        }
                        //更新商品表格
                        $("#purchaseList").jqGrid("clearGridData");

                        var goods_noArr = [];

                        if (maxRowId == undefined) {
                            maxRowId = $("#purchaseList").jqGrid('getDataIDs').length;
                        }
                        if (!purchaseOrder.object.orderGoods || purchaseOrder.object.orderGoods.length == 0)  //如果还没有商品，则添加5个空行
                        {
                            for (var i = 0; i <= 5; i++) {
                                addNewEmptyRow();
                            }
                        } else {
                            var snPacket = {};
                            scope.resultOrderGoods = result.object.orderGoods;
                            for (var i = 0; i < purchaseOrder.object.orderGoods.length; i++) {
                                goods_noArr.push(purchaseOrder.object.orderGoods[i]['goods_no']);
                                maxRowId = maxRowId + 1;
                                var discountRes = discount(purchaseOrder.object.orderGoods[i]['discount']);
                                var market_price = purchaseOrder.object.orderGoods[i]['market_price'];
                                purchaseOrder.object.orderGoods[i]['quantity'] = Math.abs(purchaseOrder.object.orderGoods[i]['quantity']);
                                purchaseOrder.object.orderGoods[i]['goodName'] = purchaseOrder.object.orderGoods[i]['name'];
                                purchaseOrder.object.orderGoods[i]['price'] = market_price;
                                purchaseOrder.object.orderGoods[i]['amount'] = accMul(market_price, purchaseOrder.object.orderGoods[i]['quantity']);
                                purchaseOrder.object.orderGoods[i]['truePrice'] = setScale(accDiv(accMul(market_price, discountRes), 100), 2);
                                purchaseOrder.object.orderGoods[i]['trueAmount'] = accMul(setScale(accDiv(accMul(market_price, discountRes), 100), 2), purchaseOrder.object.orderGoods[i]['quantity']);
                                purchaseOrder.object.orderGoods[i]['rowid'] = maxRowId;

                                var flag = false;
                                for (var sp in snPacket) {
                                    if (sp == purchaseOrder.object.orderGoods[i]['goods_no']) {
                                        flag = true;
                                        break;
                                    }
                                }
                                if (!flag) {
                                    snPacket[purchaseOrder.object.orderGoods[i]['goods_no']] = purchaseOrder.object.orderGoods[i]['packetNumber'];
                                }
                            }
                            scope.snPacketArr.push(snPacket);
                            $('#purchaseList').jqGrid('addRowData', "rowid", purchaseOrder.object.orderGoods);
                        }
                        scope.setOperation();
                        if (scope.order.state == 1 && RESOURCES.indexOf("purchaseOrderEdit") != -1) {
                            scope.updateDiscount();
                            if (goods_noArr.length > 0 && scope.order.supplierId) {
                                scope.updateSupplierPrice(scope.order.supplierId, goods_noArr, scope.updateSupplierPriceByGoodsList, {});
                            }
                        }
                        scope.loadingOrder = false;
                    },
                    error: function (result) {
                        alert(result.responseJSON.content);
                        scope.loadingOrder = false;
                        return;
                    }
                }
            );
        }
    }

    /*打开滑动电子相册*/
    var openGallery = function () {
        var scope = getScope('OrderCtrl');
        scope.$apply(function () {
            scope.initGallery()
        });
        $("#slideGallery").dialog("open");
    };

    /*关闭滑动电子相册*/
    var closeGallery = function () {
        $("#slideGallery").dialog("close");
    };

    $("#slideGallery").dialog({
        autoOpen: false,
        show: {
            effect: "blind",
            duration: 10
        },
        position: ['middle', 100],
        width: 754,
        height: 504,
        modal: true,
        resizable: false,
        open: function () {

        },
        dialogClass: "slideGallery"
    });
</script>